//
//  CZComposeViewController.swift
//  CZWeibo
//
//  Created by 左凯旭 on 16/8/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
class CZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

       setupUI()
    }

    
    //MARK: - 设置UI
    func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        
        //添加控件
        view.addSubview(textView)
        view.addSubview(bottomView)
        textView.addSubview(pictrueView)
        
        
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        bottomView.snp_makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        pictrueView.snp_makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.centerX.equalTo(textView)
        }
                 
        //监听底部按钮中的点击回调
        bottomView.closure = {[weak self](type: CZComposeBottomViewType)->() in
            
            switch type {
            case .picture:
//                print("图片")
                self?.selectedImages()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
//                print("笑脸")
                self?.switchKeyBoard()
            case .add:
                print("+")
            }
            
            
        }
        
        
        //闭包回调，选择图片
        pictrueView.closure = {[weak self] in
            
            self?.selectedImages()
        }
        
        //MARK: - 接收通知
        //注册系统通知，监听要改变的frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 注册通知 监听自定义键盘中的删除按钮点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButtonNofi", name: WBEMOTICONDELETEBUTTONNOTIFICATION, object: nil)
        
        // 注册通知 监听自定义键盘中表情按钮点击s
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonNofi:", name: WBEMOTICONBUTTONNOTIFICATION, object: nil)
        
    }
    
    
    //MARK: - 表情删除按钮通知方法的监听
    func emoticonDeleteButtonNofi(){
        //回删 ，每次一个
        textView.deleteBackward()
    }
    
    //表情按钮的点击事件
    func emoticonButtonNofi(noti:NSNotification){
        
         // 判断是否为nil 而且是否可以转成HMEmoticonModel
        guard let emoticonModel = noti.object as? CZEmoticonModel else{
            return
        }
        //判断是不是emoji表情
        if emoticonModel.isEmoji {
            //十六进制字符串
            let str = (emoticonModel.code ?? "" as NSString).emoji()
            
            textView.insertText(str)
        }else{//图片表情
            //获取当前textView已有的富文本
             let allAttr  = NSMutableAttributedString(attributedString: textView.attributedText)
            
            //创建一个文字附件
            let att = CZTextAttachment()
            //赋值
            att.emoticonModel = emoticonModel
            
            //创建图片
            let image = UIImage.emoticonsImage(emoticonModel)
            att.image = image
            //切记一定要设置bounds
            //设置行高
            let linehight = UIFont.systemFontOfSize(16).lineHeight
            att.bounds = CGRect(x: 0, y: -4, width: linehight, height: linehight)
            
            //创建一个不可变的富文本
            let attr = NSAttributedString(attachment: att)
            //获取光标的范围
            let selectRange = textView.selectedRange
            //替换
            allAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            
             // 设置allAttr font
            allAttr.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16)], range: NSRange(location: 0, length: allAttr.length))
            
            //拼接富文本 不可以 不满足要求
//            allAttr.appendAttributedString(attr)
            
           //添加富文本
            textView.attributedText = allAttr
            //更改光标
            textView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            //发送一个系统通知，隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
             // 使用代理指定协议方法
            textView.delegate?.textViewDidChange!(textView)
        }
        
    }
    
    
    //监听键盘的frame改变
    func keyboardWillChangeFrame(noti: NSNotification){
       //动画时长
    guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        
        
         // 判断他是否为nil 而且是否可以转成NSValue
        
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        
        //获取到CGRect
        let newRect = rect.CGRectValue()
        //更新约束
        bottomView.snp_updateConstraints { (make) in
             make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }
        
        //设置动画
        UIView.animateWithDuration(duration) {
            //强制刷新UI
            self.view.layoutIfNeeded()
        }
        
        
        
    }
    
    
    //MARK: - 监听导航栏按钮
   @objc private func cancelAction(){
        //释放响应者
        textView.resignFirstResponder()
    
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
   @objc private func sendAction(){
 


    // 遍历富文本
    /**
     遍历富文本
     
     - parameter <TenumerationRange: 遍历的范围
     - parameter options:            可选
     - parameter usingBlock:
     - 遍历到的结果
     - 遍历到的范围
     - 指针 是否停止
     */
   // 定义一个字符串 保存内容
     var allText: String = ""
        textView.attributedText.enumerateAttributesInRange(NSRange(location: 0,length:  textView.attributedText.length), options: []) { (result, range, _) in
             // 代表是文字附件(我自己定义的)
            if let attachment = result["NSAttachment"] as? CZTextAttachment{
//                print(attachment.emoticonModel?.chs)
                allText += attachment.emoticonModel?.chs ?? ""
            }else{
                // 普通字符串 (截取对应位置的字符串)
                
                let str = (self.textView.attributedText.string as NSString).substringWithRange(range)
                
             allText += str
            }
            
    }
        //发布微博
        pictrueView.imageList.count == 0 ? update(allText):upload(allText)

}
    
    
    //MARK: - 设置导航栏
    func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CZComposeViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendAction")
        
        //设置自定义的navifgationItem
        navigationItem.titleView = titleView
        //一开始的时候不让点击发布
        navigationItem.rightBarButtonItem?.enabled = false
        
    }
    
     //MARK: - 懒加载控件
    
    private lazy var titleView:UILabel = {
       
        let name = CZUserAccountViewModel.shareTools.userAccount!.screen_name!
        let label = UILabel()
        //显示内容
        let str = " 发微博\n\(name)"
        //设置范围
        let range = (str as NSString).rangeOfString(name)
        
        //初始化一个富文本
        let attr = NSMutableAttributedString(string: str)
        //设置富文本属性
        attr.addAttributes([NSForegroundColorAttributeName:AppThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        
        label.textAlignment = .Center
        label.numberOfLines = 0
        label.text = str
        label.sizeToFit()
        label.attributedText = attr
        return label
    }()
    
    //自定义textView加载
    private lazy var textView:UITextView = {
        let textView = CZComposeTextView()
        textView.delegate = self
        
        //给textView 里的文字设置字体大小
        textView.font = UIFont.systemFontOfSize(16)
        //设置占位的文字
        textView.placeholder = "传智博客"
        //设置颜色
        textView.color = UIColor.grayColor()
        
        //允许上下移动
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    //bottomView  的加载
    private lazy var bottomView:CZComposeBottomView = CZComposeBottomView()
    
    //pictrueView 的懒加载
    private lazy var pictrueView:CZComposePictrueView = CZComposePictrueView()
    
    //自定义表情键盘
    private lazy var emoticonKeyBoardView:CZEmotionKeyBoardView = CZEmotionKeyBoardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
    
    
    //MARK: - 析构函数
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

//MARK: - textView的 代理方法
extension CZComposeViewController:UITextViewDelegate{
    
    //有值改变之后
    func textViewDidChange(textView: UITextView) {
        
        //设置没有文字的时候不能发布
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //释放第一响应者
        self.textView.resignFirstResponder()
    }
    
}

//MARK: - 发布微博的界面

extension CZComposeViewController{
    
    //发布文字微博
    func update(status:String){
     CZNetWorkingTools.sharedTools.composeUpdate(status, succes: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //销毁当前的发布界面
           self.dismissViewControllerAnimated(true, completion: nil)
        
        //创建通知 刷新首页
        NSNotificationCenter.defaultCenter().postNotificationName("reloadHomeVC", object: nil)
        
        
            }) { (error) in
            SVProgressHUD.showErrorWithStatus("发布失败")
        }
  
    }
    
    //发布图片微博
    func upload(status:String){
        
      
        CZNetWorkingTools.sharedTools.composeUpload(status, images: pictrueView.imageList, success: { (response) in
            //销毁当前的发布界面
            self.dismissViewControllerAnimated(true, completion: nil)
            
            //创建通知 刷新首页
            NSNotificationCenter.defaultCenter().postNotificationName("reloadHomeVC", object: nil)

            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) in
            SVProgressHUD.showErrorWithStatus("发布失败")
        }
        
    }
    
    
}



//MARK: -  处理bottomView点击的事件
extension CZComposeViewController{
    
    func selectedImages(){
        
        let pickerVC = UIImagePickerController()
        //设置代理
        pickerVC.delegate = self
        
        self.presentViewController(pickerVC, animated: true, completion: nil)
    }
    
   //选择键盘
    func switchKeyBoard(){
        
        //代表现在是系统键盘
        if textView.inputView == nil {
            
            textView.inputView = emoticonKeyBoardView
            //给BottomView里的属性赋值
            bottomView.isEmoticon = true
        }else{
            //代表现在是表情键盘
            textView.inputView = nil
            bottomView.isEmoticon = false
        }
        
        //刷新
        textView.reloadInputViews()
        //成为第一响应者
        textView.becomeFirstResponder()
        
    }
    
    
}

//MARK: - pickerControl 代理方法
extension CZComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
 

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        

        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        
        
        pictrueView.addImages(UIImage.dealImageScale(image, width: 400))
    
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
   
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

















